<?php
/**
 * 公共PHP函数库
 * 相对路径: inc/pubs.php
 * 作者: 15058593138@qq.com
 */

/**
 * JSON格式返回函数
 */
function jsonMsg($code, $msg, $data = []) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['code' => $code, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * 安全过滤函数
 */
function safeStr($str) {
    return htmlspecialchars(trim($str), ENT_QUOTES, 'UTF-8');
}

/**
 * 密码加密函数(MD5+盐)
 */
function pwdHash($pwd, $salt = 'SeatBook2025') {
    return md5(md5($pwd) . $salt);
}

/**
 * 生成唯一ID
 */
function makeUnid() {
    return date('YmdHis') . rand(100000, 999999);
}

/**
 * 10进制转36进制
 */
function base36Encode($num) {
    return base_convert($num, 10, 36);
}

/**
 * 36进制转10进制
 */
function base36Decode($str) {
    return base_convert($str, 36, 10);
}

/**
 * 读取JSON文件
 */
function readJson($file) {
    if (!file_exists($file)) {
        return [];
    }
    $content = file_get_contents($file);
    $lines = explode("\n", $content);
    array_shift($lines); // 移除第一行PHP退出代码
    $json = implode("\n", $lines);
    return json_decode($json, true) ?: [];
}

/**
 * 写入JSON文件
 */
function writeJson($file, $data) {
    $content = "aaa:<?php exit();?>\n" . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    return file_put_contents($file, $content);
}

/**
 * CSV导入函数
 */
function importCsv($csvData, $table, $db) {
    $lines = explode("\n", trim($csvData));
    if (count($lines) < 2) {
        return ['code' => 0, 'msg' => 'CSV数据格式错误'];
    }
    
    $success = 0;
    $fail = 0;
    
    for ($i = 1; $i < count($lines); $i++) {
        $line = trim($lines[$i]);
        if (empty($line)) continue;
        
        $fields = str_getcsv($line, "\t");
        if (count($fields) < 2) continue;
        
        $phone = safeStr($fields[0]);
        $pwd = pwdHash($fields[1]);
        
        $sql = "INSERT INTO `{$table}` (`手机号`, `密码`) VALUES ('{$phone}', '{$pwd}')";
        if ($db->query($sql)) {
            $success++;
        } else {
            $fail++;
        }
    }
    
    return ['code' => 1, 'msg' => "导入成功{$success}条，失败{$fail}条"];
}

/**
 * 检查登录状态
 */
function checkLogin() {
    session_start();
    if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
        jsonMsg(0, '请先登录');
    }
    return $_SESSION['user_id'];
}

/**
 * 检查管理员权限
 */
function checkAdmin() {
    session_start();
    if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
        jsonMsg(0, '无权限访问');
    }
}

/**
 * 生成核验码
 */
function makeHema($date) {
    return $date . '@' . strtoupper(substr(md5(uniqid()), 0, 8));
}

/**
 * 计算座位总数
 */
function countSeats($layout) {
    $rows = explode('|', $layout);
    $total = 0;
    foreach ($rows as $row) {
        $total += intval($row);
    }
    return $total;
}

/**
 * 获取日期范围
 */
function getDateRange($days = 7) {
    $dates = [];
    for ($i = 1; $i <= $days; $i++) {
        $dates[] = date('Ymd', strtotime("+{$i} days"));
    }
    return $dates;
}
?>